package cn.com.chengq.partters.builder.b02;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.net.URL;

public class Utils {


    public static Decorator getDecorator() {
        DocumentBuilderFactory  factory = DocumentBuilderFactory.newInstance();
        Decorator result = null;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();

//            URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
//
//                @Override
//                public URLStreamHandler createURLStreamHandler(String protocol) {
//                    return new Handler();
//                }
//            });
//            new URL("classpath:/config").openConnection().getInputStream();
//            Document doc = builder.parse("classpath:/config.xml");

            URL url = ClassLoader.getSystemResource("config.xml");
            Document doc = builder.parse(url.openStream());

            NodeList classes = doc.getElementsByTagName("className");
            for (int i=0 ; i < classes.getLength(); i++) {
                Node item = classes.item(i).getFirstChild();
                String className = item.getNodeValue();
                if (className != null) {
                    System.out.println(className);
                    Class<?> c  = Class.forName(className);
                    result = (Decorator) c.newInstance();
                    break;
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return result;
    }
}
